<template>
  <el-dialog v-model="dialogVisible" v-bind="dialogConfig">
    <el-scrollbar class="scrollbar">
      <BaseForm ref="baseFormRef" v-bind="modalFormConfig" v-model:formData="formData" @change="
        change"></BaseForm>
      <slot></slot>
    </el-scrollbar>
    <template #footer v-if="showPagination">
      <span class="dialog-footer">
        <el-button type="primary" @click="confirm"> 确认 </el-button>
        <el-button @click="cancel">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="js">
import { ref, watch } from "vue";
import BaseForm from "@/old-base-ui/base-form";

const emit = defineEmits(["confirm", "change"]);
const props = defineProps({
  // 是否显示底部 操作按钮 确认 取消
  showPagination: {
    type: Boolean,
    default: true,
  },
  // 弹框表单绑定的数据
  modalFormData: {
    type: Object,
    required: true,
  },
  // 弹框表单配置
  modalFormConfig: {
    type: Object,
    required: true,
  },
  // 弹框属性配置
  dialogConfig: {
    type: Object,
    default: () => ({})
  }
});

// 是否显示弹框
let dialogVisible = ref(false);

// 表单绑定数据
const formData = ref({});

// 表单dom
const baseFormRef = ref();

// 组件之间传递过来 表单需要绑定的数据
watch(
  () => props.modalFormData,
  (newValue) => {
    formData.value = newValue;
  },
  {
    immediate: true
  }
);

// 打开弹框
const open = () => {
  dialogVisible.value = true
}

// 取消
const cancel = () => {
  dialogVisible.value = false;
};

// 表单每一项change
const change = (value, field) => {
  emit("change", value, field)
}

// 确定
const confirm = () => {
  baseFormRef.value?.submitForm((valid) => {
    if (valid) {
      dialogVisible.value = false;
      const data = { ...formData.value };
      emit("confirm", data);
    }
  });
};

defineExpose({ open });
</script>
<style scoped lang="less">
.scrollbar {
  max-height: 60vh;
  overflow-y: auto;
}
</style>